package com.cj.mytest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
@Repository
public class MyDefaultGoodsDao implements MyGoodsDao {
    @Autowired
    private DataSource dataSource;

    private ArrayList<HashMap<String,String>> list = new ArrayList<>();

    @Override
    public ArrayList<HashMap<String, String>> findAll() {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            pstat = conn.prepareStatement("SELECT * FROM tb_goods");
            rs = pstat.executeQuery();
            while(rs.next()){
                this.selectOne(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                this.close(conn,pstat,rs);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    private void selectOne(ResultSet rs) throws SQLException {
        HashMap<String,String> map = new HashMap<>();
        ResultSetMetaData rsd = rs.getMetaData();
        for(int i = 1 ; i < rsd.getColumnCount() + 1 ; i ++){
            map.put(rsd.getColumnName(i),rs.getString(rsd.getColumnName(i)));
        }
        list.add(map);
    }

    private void close(Connection conn,PreparedStatement pstat,ResultSet rs) throws SQLException {
        if(rs != null) rs.close();
        if(pstat != null) pstat.close();
        if(conn != null) conn.close();
    }
}
